/*
* 账簿数据的处理
* */
import ampub from 'ampub';
import moment from 'moment';
import { tabShowButtonClick } from '.';
import constants from '../../constants';
import afterEvent from './afterEvent';
import { updateDeptmethodItem } from './utils';

const { utils: { multiLangUtils: { getMultiLangByID }, msgUtils: { showMessage } } } = ampub;
const {
    BILL_SOURCE_TYPES,
	ACCBOOK_TABS: accbook_tabs,
	UISTATE,
	AREA: { CARD: { LOGDEPACCRUAL_TAB: logdepaccrual_tab, BASIC_INFO_AREA: basicInfoForm, FINANCE_AREA: financeForm } }
} = constants;

//财务区的显示/隐藏处理
function toggleFinanceArea() {
	const { props: { form, getUrlParam } } = this;
	let that = this;
	// 如果没有账簿 直接返回
	if (!this.state.accbooks.length) {
		/*国际化处理：没有可用的资产账簿*/
		showMessage(this.props, { content: getMultiLangByID('201201504A-000003'), color: 'info' });
		return;
	}

	//即将移除财务区
	if (that.state.financeShowFlag) {
		// 移除财务区，获取form的值并存下来，防止丢失了用户的输入数据
		if (!accbookSwitchBefore(that)) {
			//校验失败，不允许修改
			return;
		}
	}

	const status = getUrlParam('status');
	this.setState({ financeShowFlag: !this.state.financeShowFlag }, () => {
		let currentFlag = that.state.financeShowFlag;
		if (currentFlag) {
			//显示财务区， 给财务区的 form 设值
			const accbookData = that.wrapAccbookData(that.state.currentPkaccbook);
			form.setAllFormValue({
				[financeForm]: accbookData
			});
			if (status && Object.values(UISTATE).includes(status)) {
				form.setFormStatus(financeForm, status);
			}

			//更新工作量字段的编辑性
			updateDeptmethodItem.call(that, that.props, accbookData);

            /* 建卡当期计提控制 */
            showOrHideIsdepfornewcard.call(that);
		}
	});
}

/**
 * 账簿切换前
 * @param that  为卡片入口页的 this 对象
 */
function accbookSwitchBefore(that) {
	const { props: { form, getUrlParam } } = that;
	const status = getUrlParam('status');
	if (!status) {
		/*国际化处理：访问地址错误，请重新打开节点*/
		showMessage(that.props, { content: getMultiLangByID('201201504A-000006'), color: 'danger' });
		return false;
	}
	//如果是编辑态，在切换按钮之前需要获取form的值并存下来，防止丢失了用户的输入数据
	if (status === UISTATE.EDIT || status === UISTATE.ADD) {
		//编辑态的时候 校验业务区、财务区的必输项，如果有未填写的，不允许切换账簿
		// 这里有一个隐藏的问题就是：如果模板上设置了必输项，但是visible=false, 将导致无法在界面上看到必输项的校验结果
		//这是平台校验方法隐藏的一个问题（截止到2018-6-20）
		let isCheck = form.isCheckNow([ basicInfoForm, financeForm ]);
		if (isCheck) {
			that.syncDataForCommit();
		}
		return isCheck;
	}

	return true;
}

//账簿按钮切换处理
function accbookSwitchHandler(pk_accbook) {
	const { props: { form, cardTable, getUrlParam } } = this;
	let that = this;
	let validate = accbookSwitchBefore(that);
	if (!validate) {
		//如果没有验证通过，不允许切换账簿
		return;
	}

	this.setState(
		{
			currentPkaccbook: pk_accbook,
			depEchartsHide: true,
			dep_tab_style: 'table'
		},
		() => {
			//更新界面数据
			let { currentPkaccbook } = that.state;
			// 更新basicInfoForm数据
			that.basicInfoData = that.getAccbookDataByPkaccbook(currentPkaccbook);
			const basicInfoData4Form = that.wrapBasicInfoData();

			// 更新财务区数据
			const accbookData = that.wrapAccbookData(currentPkaccbook);
			form.setAllFormValue({
				[financeForm]: accbookData,
				[basicInfoForm]: basicInfoData4Form
			});

			// 账簿变化，需要处理对应的折旧方法， 走一下编辑后事件
			// 参考：nc nc.ui.fa.asset.event.accbook.HeadDataChangeEventHandler
			const status = getUrlParam('status');
			if (status === UISTATE.EDIT || status === UISTATE.ADD) {
				let newValue = form.getFormItemsValue(financeForm, 'pk_depmethod');
				afterEvent.call(that, that.props, financeForm, 'pk_depmethod', newValue, null, null, null, true);
			}

			//收起与账簿相关的页签，因为页签的数据是懒加载的
			cardTable.toggleCardTable(accbook_tabs, false);

			// 刷新计提利息记录页签
			refreshDepaccrualTab.call(this);
		}
	);
}

/**
 * 刷新计提利息记录页签
 */
function refreshDepaccrualTab() {
	const { props: { cardTable } } = this;
	cardTable.setTableData(logdepaccrual_tab, { rows: [] });
	cardTable.toggleCardTable(logdepaccrual_tab, true);
	tabShowButtonClick.call(this, this.props, logdepaccrual_tab, true);
}

/**
 * 建卡当期计提复选框的显示控制
 * 
 */
function showOrHideIsdepfornewcard() {
	let { state: { financeShowFlag }, props: { form, getUrlParam, pageConfig: { newasset_flag } } } = this;

	//录入原始卡片 不应用该元素
	if (newasset_flag == 0) {
		// 由初始化模板控制
		return;
	}

	// 财务区未展开
	if (!financeShowFlag) {
		return;
	}

     // 不需要展示的业务
    if ([ UISTATE.BROWSE, UISTATE.EDIT ].includes(status)) {
		let bill_source = form.getFormItemsValue(basicInfoForm, 'bill_source').value;
		let hideBusiness = [
			/** 3 调入单据 */
			BILL_SOURCE_TYPES.deploy_in_src,
			/** 4 拆分单据 */
			BILL_SOURCE_TYPES.split_src,
			/** 5 合并单据 */
			BILL_SOURCE_TYPES.conbin_src
		].includes(bill_source);
        if(hideBusiness){
            return;
        }
	}

	let visible = false;
	let status = getUrlParam('status') || UISTATE.BLANK;

	if ([ UISTATE.ADD, UISTATE.BROWSE, UISTATE.EDIT ].includes(status)) {
		// 开始使用日期会计期间
		let begin_period = form.getFormItemsValue(financeForm, 'begin_period').value;
		// 建卡日期会计期间
		let business_period = form.getFormItemsValue(financeForm, 'business_period').value;

		let begin = moment(begin_period, 'YYYY-MM');
		let business = moment(business_period, 'YYYY-MM');

		if (begin.isBefore(business)) {
			visible = true;
		}
	}

	let visibleCurr = form.getFormItemsVisible(financeForm, 'isdepfornewcard');
	if (visible != visibleCurr) {
		form.setFormItemsVisible(financeForm, { isdepfornewcard: visible });
        // 建卡当期计提：再次赋默认值为Y
        form.setFormItemsValue(financeForm, { isdepfornewcard: { value: true } });
	}
}

export { toggleFinanceArea, accbookSwitchHandler, showOrHideIsdepfornewcard };

